<template>
  <el-dialog v-model="dialogTableVisible2" :show-close="true" width="60%">
    <div style="height: 465px; overflow: hidden">
      <div style="position: absolute; top: 5px">
        <el-input
          style="width: 150px; margin-left: 2px"
          v-model="inputDjBh2"
          placeholder="单件编号"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 150px; margin-left: 2px"
          v-model="inputK3Mc2"
          placeholder="物料名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-select
          style="width: 150px; margin-left: 2px; margin-top: 2px"
          v-model="inputflMc2"
        >
          <el-option label="辊" value="02.06"></el-option>
          <el-option label="刀" value="02.12"></el-option>
        </el-select>
        <el-button style="margin-left: 5px" @click="searc3Kh" type="primary"
          >查询</el-button
        >
        <el-button style="margin-left: 5px" @click="putK3Wl" type="primary"
          >添加</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          ref="table2"
          border
          stripe
          :data="tableData2"
          @row-click="RowClick2"
          :cell-style="cellStyle2"
          :header-cell-style="headerCellStyle"
          max-height="420px"
          height="420px"
          @selection-change="handleSelectionChange2"
          show-overflow-tooltip
        >
          <el-table-column type="selection" width="65" align="center" />
          <el-table-column prop="zh" label="组号" width="120" align="center" />
          <el-table-column prop="djBh" label="单件编号" width="120" align="center" />
          <el-table-column prop="k3WlBm" label="物料编码" width="150" align="center" />
          <el-table-column prop="k3Mc" label="物料名称" width="150" align="center" />
          <el-table-column prop="flMc" label="分类" width="80" align="center" />
          <el-table-column prop="gzmDcMxcs" label="磨削次数" width="80" align="center" />
          <el-table-column prop="lx" label="类型" width="80" align="center" />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="page2"
            v-model:page-size="limit2"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total2"
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 页面布局 -->
  <div
    v-if="dialogTableVisible1"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <el-button @click="flushed" type="primary" v-if="flushedPermissions7">
            刷新</el-button
          >
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
        修改业务员</el-button
      > -->
          <el-button @click="addRow" type="primary" v-if="primaryPermissions7"
            >增行</el-button
          >

          <el-button
            type="primary"
            @click="insertMaterialsFixed"
            v-if="showInsertButton && insertMaterialsFixedPermissions7"
            >保存</el-button
          >
          <el-button
            type="primary"
            @click="updateMaterialsFixed"
            v-if="!showInsertButton && updateMaterialsFixedPermissions7"
            >保存</el-button
          >
          <el-button
            @click="getDeleteRowData"
            v-if="getDeleteRowDataPermissions7"
            type="danger"
            >删除</el-button
          >
          <el-button
            @click="OFFdialogTableVisible"
            v-if="OFFdialogTableVisiblePermissions7"
            type="danger"
            >关闭</el-button
          >
        </div>
      </div>
      <!-- <div class="vertical-line2"></div>
      <div class="vertical-line4"></div> -->
      <!-- title -->
      <div
        ref="titleDiv"
        :style="{
          backgroundColor: 'rgba(247, 247, 247, 0.903)',
          height: inputHeight - 30 + 'px',
          width: screenWidth + 'px',
        }"
      >
        <el-form :model="form" class="demo-form-inline" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">单据编号</label>
            <el-input
              style="width: 180px"
              v-model="form.documentNumber"
              disabled
              placeholder="自动生成"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">单据时间</label>
            <el-input
              style="width: 180px"
              v-model="form.djsj"
              disabled
              placeholder="自动生成"
              clearable
            />
          </el-form-item>
        </el-form>
        <el-form :model="form" class="demo-form-inline" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"
              ><span style="color: red">*</span>工序</label
            >
            <el-input style="width: 180px" v-model="form.gx" placeholder="" clearable />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"
              ><span style="color: red">*</span>设备</label
            >
            <el-input style="width: 180px" v-model="form.sb" placeholder="" clearable />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"
              ><span style="color: red">*</span>班组</label
            >
            <el-input
              style="width: 180px"
              v-model="form.banZu"
              placeholder=""
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <!-- 子表添加 -->
      <el-form :inline="true" :model="formInline">
        <div
          :style="{
            width: screenWidth + 'px',
            'max-height': tableHeight + 130 - 42 + 'px',
            'overflow-y': 'auto',
            'overflow-x': 'hidden',
            'scrollbar-width': 'thin',
          }"
        >
          <table>
            <tr class="sticky-header" style="z-index: 99">
              <th style="width: 50px" class="table-header">序号</th>
              <th style="width: 50px" class="table-header">
                <el-checkbox @change="toggleSelectAll" v-model="selectAll"></el-checkbox>
              </th>
              <th style="width: 180px" class="table-header">组号</th>
              <th style="width: 180px" class="table-header">辊号</th>
              <th style="width: 150px" class="table-header">物料编码</th>
              <th style="width: 150px" class="table-header">物料名称</th>
              <th style="width: 150px" class="table-header">类型</th>
              <th style="width: 120px" class="table-header">磨削次数</th>
              <th style="width: 120px" class="table-header red-asterisk">人数</th>
              <th style="width: 120px" class="table-header red-asterisk">耗材名称</th>
              <th style="width: 120px" class="table-header red-asterisk">规格</th>
              <th style="width: 120px" class="table-header red-asterisk">数量</th>
              <th style="width: 120px" class="table-header red-asterisk">单位</th>
              <th style="width: 80px" class="table-header">操作</th>
            </tr>
            <tr v-for="(formData, index) in formDataList" :key="index">
              <td style="text-align: center">{{ index + 1 }}</td>
              <td style="text-align: center">
                <el-checkbox v-model="formData.selected"></el-checkbox>
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.zh"
                  :readonly="true"
                  placeholder=""
                  clearable
                  @click="openWlbm(index)"
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.djBh"
                  :readonly="true"
                  placeholder=""
                  clearable
                  @click="openWlbm(index)"
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.k3WlBm"
                  :readonly="true"
                  placeholder=""
                  clearable
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.k3Mc"
                  :readonly="true"
                  placeholder=""
                  clearable
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.lx"
                  :readonly="true"
                  placeholder=""
                  clearable
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.gzmDcMxcs"
                  :readonly="true"
                  placeholder=""
                  clearable
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.rs"
                  placeholder=""
                  clearable
                  @blur="() => handleBlur('rs', index)"
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input v-model="formData.hcMc" placeholder="" clearable />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input v-model="formData.gg" placeholder="" clearable />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input
                  v-model="formData.sl"
                  placeholder=""
                  clearable
                  @blur="() => handleBlur('sl', index)"
                />
              </td>
              <td
                class="table-value"
                style="width: 100px; text-align: left; padding-left: 5px"
              >
                <el-input v-model="formData.dw" placeholder="" clearable />
              </td>

              <td>
                <el-button
                  style="height: 30px; margin-top: 1px"
                  type="danger"
                  @click="handleDeletes(index)"
                  >删除</el-button
                >
              </td>
            </tr>
            <!-- 合计行 -->
            <tr
              style="
                text-align: center;
                position: sticky;
                bottom: -1px;
                background-color: #ddd;
                z-index: 99;
              "
            >
              <!-- <td colspan="9">合计：</td> -->
              <td>合计:</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </table>
        </div>
      </el-form>
      <div style="background-color: rgba(247, 247, 247, 0.903)">
        <el-form
          :model="form"
          class="demo-form-inline"
          :inline="true"
          :style="{
            backgroundColor: ' rgba(247, 247, 247, 0.903)',
            width: screenWidth - 10 + 'px',
            height: '120px',
          }"
        >
          <el-form-item class="lab" style="margin-right: 0">
            <el-input
              :style="{
                width: '180vh',
                zIndex: '99',
                backgroundColor: '#ffffff',
                resize: 'none',
                height: '50px',
              }"
              type="textarea"
              v-model="form.bz"
              placeholder="备注"
              clearable
            />
          </el-form-item>

          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">制单人</label>
            <el-input
              v-model="form.zdr"
              style="width: 200px; height: 3.5vh"
              disabled
              placeholder="制单人"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">制单时间</label>
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 200px"
                disabled
                v-model="form.zdsj"
                type="datetime"
                placeholder="制单时间"
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">修改人</label>
            <el-input
              style="width: 180px"
              v-model="form.xgr"
              disabled
              placeholder="修改人"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">修改时间</label>
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 200px"
                disabled
                v-model="form.xgsj"
                type="datetime"
                placeholder="修改时间"
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">审核人</label>
            <el-input
              style="width: 200px"
              v-model="form.shr"
              disabled
              placeholder="审核人"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0; heiht: 3.5vh">
            <label class="lab" style="width: 100px; padding-right: 5px">审核时间:</label>
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 200px"
                disabled
                v-model="form.shsj"
                type="datetime"
                placeholder="审核时间"
              />
            </el-config-provider>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <div>
    <el-container>
      <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
        <!-- 头部按钮 -->
        <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
          <div>
            <el-button
              @click="searchButton"
              v-if="searchButtonPermissions7"
              type="primary"
            >
              查询</el-button
            >
            <el-button @click="addDejz" type="success">新增</el-button>
            <el-button @click="handleWarning0" type="warning">审核</el-button>
            <el-button @click="handleWarning1" type="danger">弃审</el-button>
          </div>
        </el-row>
        <div
          style="margin-left:6rem;height: 30px;width=100%; background:rgb(241,244,243);margin-bottom: 0;position: relative; display: flex; justify-content: flex-start;"
        >
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="Dejz_djBh"
            placeholder="单据编号"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="Dejz_k3Mc"
            placeholder="工序"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-header>
      <el-container>
        <el-container>
          <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
            <el-table
              v-loading="loading"
              ref="table"
              :data="tableData"
              border
              stripe
              :cell-style="cellStyle"
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              @row-dblclick="handleRowClick"
              @row-click="RowClick"
              :row-style="rowState"
              :row-key="(row) => row.id"
              :max-height="screenHeight"
              :height="screenHeight"
              :summary-method="getSummaries"
              empty-text="无数据"
              show-summary
            >
              <el-table-column fixed type="index" width="60" align="center" />
              <el-table-column fixed type="selection" width="50" align="center" />
              <el-table-column fixed prop="id" label="id" width="150" align="center" />
              <el-table-column
                fixed
                prop="documentNumber"
                label="单据编号"
                width="150"
                align="center"
              />
              <el-table-column prop="gx" label="工序" width="80" align="center" />
              <el-table-column prop="sb" label="设备" width="80" align="center" />
              <el-table-column prop="banZu" label="班组" width="80" align="center" />
              <el-table-column prop="zt" label="状态" width="80" align="center" />
              <el-table-column prop="shZt" label="审核状态" width="80" align="center" />
              <el-table-column prop="djsj" label="单据时间" width="180" align="center" />
              <el-table-column prop="bz" label="备注" width="80" align="center" />
              <el-table-column
                prop="sqrGh"
                label="申请人工号"
                width="80"
                align="center"
              />
              <el-table-column
                prop="sqrXm"
                label="申请人姓名"
                width="120"
                align="center"
              />
              <el-table-column
                prop="sqrBm"
                label="申请人部门"
                width="120"
                align="center"
              />
              <el-table-column prop="sqSj" label="申请时间" width="180" align="center" />
              <el-table-column
                prop="shrGh"
                label="审核人工号"
                width="80"
                align="center"
              />
              <el-table-column
                prop="shrXm"
                label="审核人姓名"
                width="120"
                align="center"
              />
              <el-table-column
                prop="shrBm"
                label="审核人部门"
                width="120"
                align="center"
              />
              <el-table-column prop="shSj" label="审核时间" width="180" align="center" />
              <el-table-column
                prop="xgrGh"
                label="修改人工号"
                width="80"
                align="center"
              />
              <el-table-column
                prop="xgrXm"
                label="修改人姓名"
                width="120"
                align="center"
              />
              <el-table-column
                prop="xgrBm"
                label="修改人部门"
                width="120"
                align="center"
              />
              <el-table-column prop="xgSj" label="修改时间" width="180" align="center" />
            </el-table>
          </el-main>
          <el-footer style="height: 20px">
            <div class="demo-pagination-block">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="limit"
                :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
                :small="true"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { ElTable, TableColumnCtx, ElMessageBox } from "element-plus";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  FormRules,
  FormInstance,
} from "element-plus";
import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";

// 日期中文
import zhCn from "element-plus/dist/locale/zh-cn.mjs";

const isDdslDisabledYwy = ref(true);
const router = useRouter();
// 权限控制
const searcpczPermissions7 = ref(false);
const searcpytPermissions7 = ref(false);
const searchYwyPermissions7 = ref(false);
const updatYwyYwyPermissions7 = ref(false);
const searc3KhPermissions7 = ref(false);
const put3KhPermissions7 = ref(false);
const updateK3Permissions7 = ref(false);
const searchKhPermissions7 = ref(false);
const upKhPermissions7 = ref(false);
const flushedPermissions7 = ref(false);
const primaryPermissions7 = ref(false);
const getDeleteRowDataPermissions7 = ref(false);
const insertMaterialsFixedPermissions7 = ref(false);
const updateMaterialsFixedPermissions7 = ref(false);
const OFFdialogTableVisiblePermissions7 = ref(false);
const searchButtonPermissions7 = ref(false);
const handleAction1Permissions7 = ref(false);
const handleWarning0Permissions7 = ref(false);
const handleWarning1Permissions7 = ref(false);
const handleDeletePermissions7 = ref(false);

const menuId = ref(7);
const buttonVariables = {
  searcpczPermissions7,
  searcpytPermissions7,
  searchYwyPermissions7,
  updatYwyYwyPermissions7,
  searc3KhPermissions7,
  put3KhPermissions7,
  updateK3Permissions7,
  searchKhPermissions7,
  upKhPermissions7,
  flushedPermissions7,
  primaryPermissions7,
  getDeleteRowDataPermissions7,
  insertMaterialsFixedPermissions7,
  updateMaterialsFixedPermissions7,
  OFFdialogTableVisiblePermissions7,
  searchButtonPermissions7,
  handleAction1Permissions7,
  handleWarning0Permissions7,
  handleWarning1Permissions7,
  handleDeletePermissions7,
};
// 弹窗
const screenWidth = ref(window.innerWidth);
// titleDiv
const inputHeight = ref(200);

const handleResize = () => {
  screenWidth.value = window.innerWidth;
  console.log("宽度" + screenWidth.value);
  screenWidth.value = screenWidth.value - 96;
  inputHeight.value = 100;
};
handleResize();
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");

  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();

// 退出登录
const handleCommand = (command: string | number | object) => {
  if (command == "a") {
    Cookies.remove("userName");
    router.push("/");
  }
};
// 计算高度
const screenHeight = ref(null);
const dynamicHeight = ref(null);
const dynamicHeightYtfl = ref(null);
const tableHeight = ref(null);

const getScreenHeight = () => {
  screenHeight.value = window.innerHeight - 146 - 42 + 55;
  dynamicHeight.value = `${window.innerHeight - 55 + 55}px`;
  dynamicHeightYtfl.value = window.innerHeight - 120 + 55;
  tableHeight.value = window.innerHeight - 435 + 19 + 55;
  console.log("高度" + window.innerHeight);
  console.log("子表:" + tableHeight.value);
};
getScreenHeight();
const activeIndex = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {};
// 主表
const dialogTableVisible = ref(false);
const dialogTableVisible1 = ref(false);
const dialogTableVisible2 = ref(false);

const checkList = ref([]);
const checkList1 = ref([]);
const showInsertButton = ref(true);
const IsXg = ref(true);
let idUpdate = 0;
const handleRowClick = (row) => {
  idUpdate = row.id;
  showInsertButton.value = false;
  dialogTableVisible1.value = true;
  form.documentNumber = row.documentNumber;
  form.djsj = row.djsj;
  form.gx = row.gx;
  form.sb = row.sb;
  form.banZu = row.banZu;
  form.bz = row.bz;
  form.zdr = row.sqrXm;
  form.zdsj = row.sqSj;
  form.shr = row.shrXm;
  form.shsj = row.shSj;
  form.xgr = row.xgrXm;
  form.xgsj = row.xgrSj;
  const userName = Cookies.get("userName");
  axios({
    url: "/get/McHc/List",
    method: "post",
    data: {
      userName: userName,
      id: row.id,
    },
  }).then((row) => {
    formDataList.value = row.data;
    for (let a = 0; a < 21; a++) {
      addRow();
    }
    dialogTableVisible1.value = true;
  });
};
const handleCheckboxChange = (label) => {
  checkList.value = [label];
};
const handleCheckboxChange1 = (label) => {
  checkList1.value = [label];

  for (let lengthCsfs = 0; lengthCsfs < formDataList.value.length; lengthCsfs++) {
    if (!formDataList.value[lengthCsfs].wlbm == "") {
      formDataList.value[lengthCsfs].csfs = checkList1.value[0];
    }
  }
};
const form = reactive({
  fabh: "",
  djrq: "",
  cswd: "",
  cpyt: "",
  kh: "",
  cz: "",
  hd: "",
  dwjs: "",
  bz: "",
  zdr: "",
  zdsj: "",
  xgr: "",
  xgsj: "",
  shr: "",
  shsj: "",
  famc: "",
  documentNumber: "",
  djsj: "",
  gx: "",
  sb: "",
  banZu: "",
});
const initialFormState = reactive({
  hcBh: "",
  hcMc: "",
  gg: "",
  sl: "",
  dw: "",
  bz: "",
  djBh: "",
  gzmDcMxcs: "",
  rs: "",
  hysj: "",
  sqrGh: "",
  sqrXm: "",
  sqBm: "",
  sqSj: "",
  shrGh: "",
  shrXm: "",
  shrBm: "",
  shrSj: "",
  xgrGh: "",
  xgrXm: "",
  xgrBm: "",
  xgrSj: "",
});
const hcTable = reactive({
  hcBh: "",
  hcMc: "",
  gg: "",
  sl: "",
  dw: "",
  bz: "",
  djBh: "",
  gzmDcMxcs: "",
  rs: "",
  hysj: "",
  sqrGh: "",
  sqrXm: "",
  sqBm: "",
  sqSj: "",
  shrGh: "",
  shrXm: "",
  shrBm: "",
  shrSj: "",
  xgrGh: "",
  xgrXm: "",
  xgrBm: "",
  xgrSj: "",
} as any);
// 子表
let selectedRowIndex = -1; // 初始化为-1，表示没有选中的行
let clearSelection = true;
// 方法：获取已勾选数据
const getSelectedRowsData = () => {
  const selectedData = formDataList.value.filter((formData) => formData.selected);
  // 在这里可以执行想要的操作，例如将 selectedData 发送到服务器或者在控制台中打印出来
};
//多选
const selectAll = ref(false);
const toggleSelectAll = () => {
  for (const formData of formDataList.value) {
    formData.selected = selectAll.value === true;
  }
};
// 单位基数
const handleChangeDwjs = () => {
  if (!isNaN(parseFloat(form.dwjs)) && isFinite(form.dwjs)) {
    var dwjsFloat = parseFloat(form.dwjs).toFixed(4);
    form.dwjs = dwjsFloat;
    for (let length = 0; length < formDataList.value.length; length++) {
      if (!formDataList.value[length].wlbm == "") {
        formDataList.value[length].dwjs = dwjsFloat;
      }
    }
    return;
  }
  form.ddsl = "";
};
// 计算金额
const handleChange = (field, index) => {
  //   formDataList.value[index].issl = true;
  let inputValue = formDataList.value[index][field];

  // formDataList.value[index].[field] = true;
  inputValue = parseFloat(inputValue).toFixed(4);

  // const inputValue = formDataList.value[index][field];
  const isValidInput = /^-?\d+(\.\d{0,4})?$/.test(inputValue);

  if (isValidInput) {
    // 如果是有效的数字，更新 formDataList
    formDataList.value[index][field] = parseFloat(inputValue);
    if (field === "bzsl") {
      formDataList.value[index].issl = true;
    }

    if (field === "bzdj") {
      formDataList.value[index].isdj = true;
    }

    // 检查是否有数字值
    const hasBzsl = typeof formDataList.value[index].bzsl === "number";
    const hasBzdj = typeof formDataList.value[index].bzdj === "number";
    // 如果 bzsl 和 bzdj 都有数字值，计算 bzje
    if (hasBzsl && hasBzdj) {
      const bzsl = formDataList.value[index].bzsl || 0;
      const bzdj = formDataList.value[index].bzdj || 0;

      // 计算标准金额，四舍五入保留两位小数
      formDataList.value[index].bzje = (bzsl * bzdj).toFixed(2);
      return;
    }
    formDataList.value[index].bzje = 0;
  } else {
    // 如果输入值不符合要求，进行相应的处理，比如清空输入框或者给出提示
    formDataList.value[index][field] = null;
    formDataList.value[index].bzje = 0;
    if (field === "bzsl") {
      formDataList.value[index].issl = false;
    }

    if (field === "bzdj") {
      formDataList.value[index].isdj = false;
    }
    console.warn(`Invalid numeric input for ${field} in row ${index}`);
  }
};

type ColumnKey =
  | "wlbm"
  | "wlmc"
  | "wlgg"
  | "jldw"
  | "bzsl"
  | "bzdj"
  | "bz"
  | "csfs"
  | "dwjs";
//合计行
const calculateTotal = (columnKey: ColumnKey) => {
  let total = 0;
  for (const formData of formDataList.value) {
    // 将字符串转换为数字，然后累加
    total += parseFloat(formData[columnKey]) || 0;
  }
  // 返回合计值
  return total.toFixed(4); // 这里假设合计值需要保留两位小数
};
//删除一行
const handleDeletes = (index: number) => {
  formDataList.value.splice(index, 1);
  if (formDataList.value.length === 0) {
    addRow();
  }
};
//删除已勾选
const getDeleteRowData = () => {
  const selectedIndexes: any = [];

  // 找到已勾选行的索引
  formDataList.value.forEach((formData, index) => {
    if (formData.selected) {
      selectedIndexes.push(index);
    }
  });

  // 删除已勾选行
  for (let i = selectedIndexes.length - 1; i >= 0; i--) {
    formDataList.value.splice(selectedIndexes[i], 1);
  }

  // 如果没有剩余行数据，添加一行
  if (formDataList.value.length === 0) {
    addRow();
  }
  selectAll.value = false;
};
const formInline = ref([]);
const formDataList = ref([
  {
    djBh: "",
    k3WlBm: "",
    k3Mc: "",
    flMc: "",
    gzmDcMxcs: "",
    rs: "",
    hcMc: "",
    gg: "",
    sl: "",
    dw: "",
    bz: "",
    selected: false,
    issl: false,
    isdj: false,
  },
]);

// 添加按钮点击时，添加一组空表单数据
const addRow = () => {
  formDataList.value.push({
    zh: "",
    djBh: "",
    k3WlBm: "",
    k3Mc: "",
    lx: "",
    gzmDcMxcs: "",
    rs: "",
    hcMc: "",
    gg: "",
    sl: "",
    dw: "",
    bz: "",
    selected: false,
  });
};
const handleSizeChange2 = (val: number) => {
  getK3FlxxDG();
};
const handleCurrentChange2 = (val: number) => {
  getK3FlxxDG();
};
// k3修改调试
const putK3Wl = (index) => {
  let indexK3 = 0;

  for (let k = 0; k < selectedRows2.value.length; k++) {
    // 验证
    for (let i = 0; i < formDataList.value.length; i++) {
      if (formDataList.value[i].djBh === selectedRows2.value[k].djBh) {
        const duplicateRowIndex = i + 1; // 行数从1开始
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: `第 ${duplicateRowIndex} 行已经存在相同的单据编号:${selectedRows2.value[k].djBh}`,
          type: "error",
        });
        // ElMessage.error(
        //   `第 ${duplicateRowIndex} 行已经存在相同的单据编号:${selectedRows2.value[k].djBh}`
        // );
        return;
      }
    }
    formDataList.value[indexK3bm + indexK3].zh = selectedRows2.value[k].zh;
    formDataList.value[indexK3bm + indexK3].djBh = selectedRows2.value[k].djBh;
    formDataList.value[indexK3bm + indexK3].k3WlBm = selectedRows2.value[k].k3WlBm;
    formDataList.value[indexK3bm + indexK3].k3Mc = selectedRows2.value[k].k3Mc;
    formDataList.value[indexK3bm + indexK3].lx = selectedRows2.value[k].lx;
    formDataList.value[indexK3bm + indexK3].gzmDcMxcs = selectedRows2.value[k].gzmDcMxcs;
    indexK3++;
  }
  dialogTableVisible2.value = false;
  // bzslinput.value[indexK3bm].focus();
};
const searc3Kh = (index) => {
  getK3FlxxDG();
};
var indexK3bm = 0;
const openWlbm = (index) => {
  indexK3bm = index;
  dialogTableVisible2.value = true;
  getK3FlxxDG();
};
const getK3FlxxDG = () => {
  axios({
    url: "/MC/get/hcxx",
    method: "post",
    data: {
      djBh: inputDjBh2.value,
      k3Mc: inputK3Mc2.value,
      parentId: inputflMc2.value,
      page: page2.value,
      limit: limit2.value,
      zt: 7,
    },
  }).then((res) => {
    const K3FlXxList = res.data;
    tableData2.value = [];
    if (K3FlXxList.length == 0) {
      total2.value = 0;
      return;
    }
    tableData2.value = K3FlXxList;
    total2.value = K3FlXxList[0].total;
  });
};

// 背景色
const verticalLine3 = ref(null);
// 分页
const page = ref(1);
const page1 = ref(1);
const page2 = ref(1);
const page3 = ref(1);
const page4 = ref(1);
const page5 = ref(1);
const limit = ref(50);
const limit1 = ref(50);
const limit2 = ref(50);
const limit3 = ref(50);
const limit4 = ref(50);
const limit5 = ref(50);
const total = ref(10);
const total1 = ref(10);
const total2 = ref(10);
const total3 = ref(10);
const total4 = ref(10);
const total5 = ref(10);
const loading = ref(false);
const selectCookies = () => {};
selectCookies();

const handleSizeChange = (val: number) => {
  selectpurposes();
};
const handleCurrentChange = (val: number) => {
  selectpurposes();
};
// 搜索框
const Dejz_k3Mc = ref("");
const Dejz_djBh = ref("");
const Dejz_lx = ref("辊");
const inputMc = ref("");
const inputBm = ref("");
const inputKhBm = ref("");
const inputKhMc = ref("");
const inputK3Bm = ref("");
const inputK3Mc = ref("");
const inputywy = ref("");
const inputywygh = ref("");
const inputytbm = ref("");
const inputytfl = ref("");
const inputytdy = ref("");
const inputCzbm = ref("");
const inpuCzfl = ref("");
const inputCzyt = ref("");
const inputDjBh2 = ref("");
const inputK3Mc2 = ref("");
const inputflMc2 = ref("");

const userName = Cookies.get("userName");
// 修改
const submitAside2 = () => {
  ElMessageBox.confirm("确认提交吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      const userName = Cookies.get("userName");
      if (!userName) {
        router.push("/");
        return;
      }
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      axios({
        url: "/update/hcxx",
        method: "post",
        data: {
          userName: userName,
          currentFormattedDateTime: currentFormattedDateTime,
          hcBh: hcTable.hcBh,
          hcMc: hcTable.hcMc,
          gg: hcTable.gg,
          sl: hcTable.sl,
          dw: hcTable.dw,
          bz: hcTable.bz,
          djBh: hcTable.djBh,
          gzmDcMxcs: hcTable.gzmDcMxcs,
          rs: hcTable.rs,
          hysj: hcTable.hysj,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.data,
            type: "success",
          });
          dialogTableVisible1.value = false;
          selectpurposes();
          return;
        }
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: res.data.msg,
          type: "error",
        });
      });
    })
    .catch(() => {});
};
// 新增
const submitAside1 = () => {
  ElMessageBox.confirm("确认提交吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      const userName = Cookies.get("userName");
      if (!userName) {
        router.push("/");
        return;
      }
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      axios({
        url: "/add/hcxx",
        method: "post",
        data: {
          userName: userName,
          currentFormattedDateTime: currentFormattedDateTime,
          hcBh: hcTable.hcBh,
          hcMc: hcTable.hcMc,
          gg: hcTable.gg,
          sl: hcTable.sl,
          dw: hcTable.dw,
          bz: hcTable.bz,
          djBh: hcTable.djBh,
          gzmDcMxcs: hcTable.gzmDcMxcs,
          rs: hcTable.rs,
          hysj: hcTable.hysj,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.data,
            type: "success",
          });
          dialogTableVisible1.value = false;
          selectpurposes();
          return;
        }
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: res.data.msg,
          type: "error",
        });
      });
    })
    .catch(() => {});
};
const deleteHc = () => {
  if (selectedRows.value.length == 1) {
    ElMessageBox.confirm("确认删除吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        const userName = Cookies.get("userName");
        if (!userName) {
          router.push("/");
          return;
        }
        const currentFormattedDateTime = getCurrentFormattedDateTime();
        axios({
          url: "/del/hcxx",
          method: "post",
          data: {
            currentFormattedDateTime: currentFormattedDateTime,
            userName: userName,
            hcBh: selectedRows.value[0].hcBh,
            // djBh: selectedRows.value.map((row) => row.djBh),
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: res.data.data,
              type: "success",
            });
            selectpurposes();
            return;
          }
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.msg,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "请选择一行进行删除操作",
      type: "warning",
    });
    // ElMessage.warning("请选择一行进行删除操作");
  }
};
const addDejz = () => {
  flushed();
  // formDataList.value = selectedRows.value;
  for (let a = 0; a < 21; a++) {
    addRow();
  }
  IsXg.value = false;
  dialogTableVisible1.value = true;
  dialogTableVisible2.value = true;
  openWlbm(0);

  hcTable.value = { ...initialFormState };
};
// 搜索
const searchButton = () => {
  selectpurposes();
};
// const input1 = ref('')
// 合计行
interface SummaryMethodProps<T = Product> {
  columns: TableColumnCtx<T>[];
  data: T[];
}
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }

    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = ` ${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "";
    }
    sums[index] = "";
  });

  for (let hj = 0; hj < sums.length; hj++) {
    var val = sums[hj];
    // !isNaN(parseFloat(value)) && isFinite(value);
    if (!isNaN(parseFloat(val)) && isFinite(val)) {
      sums[hj] = parseFloat(sums[hj]).toFixed(2);
      continue;
    }
  }
  return sums;
};

// 弹窗
const buttonText = ref("添加用途分类");
// 添加按钮
// 制单时间
const ywy = ref("");
const zdrbm = ref("");
const ywbm = ref("");
const ywygh = ref("");
const ywbmgh = ref("");
const handleAction1 = () => {
  if (selectedRows.value.length != 0) {
    ElMessageBox.confirm("确认提交吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        const userName = Cookies.get("userName");
        if (!userName) {
          router.push("/");
          return;
        }
        let shouldContinue = true; // 标志变量

        selectedRows.value.forEach((row, index) => {
          if (row.shZt === "待审核") {
            console.log(row);
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: `已提交数据不能重复提交`,
              type: "error",
            });
            shouldContinue = false; // 设置标志变量为 false
          }
        });
        if (!shouldContinue) {
          return;
        }
        const currentFormattedDateTime = getCurrentFormattedDateTime();
        axios({
          url: "/MC/upDate/K3WlXx/ShZt",
          method: "post",
          data: {
            currentFormattedDateTime: currentFormattedDateTime,
            userName: userName,
            djBh: selectedRows.value.map((row) => row.djBh),
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: res.data.data,
              type: "success",
            });
            selectpurposes();
            return;
          }
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.msg,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "请选择一行进行审核操作",
      type: "warning",
    });
    // ElMessage.warning("请选择一行进行审核操作");
  }
};

// 关闭弹窗
const OFFdialogTableVisible = () => {
  dialogTableVisible1.value = false;
};
const handleAction2 = () => {};

// 进入页面
const selectpurposes = () => {
  // 查看是否登录
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  axios({
    url: "/select/Hao/Cai",
    method: "post",
    data: {
      documentNumber: Dejz_djBh.value,
      gx: Dejz_k3Mc.value,
      userName: userName,
      page: page.value,
      limit: limit.value,
      zt: 7,
    },
  }).then((res) => {
    console.log(res.data);
    const K3FlXxList = res.data;
    if (K3FlXxList.length == 0) {
      total.value = 0;
      loading.value = false;
      tableData.value = [];
      return;
    }
    let statusMapping = {
      0: "待领",
      1: "待流转",
      2: "待磨削",
      3: "磨削中",
      4: "磨完",
      5: "异常",
      6: "废弃",
      7: "待耗用",
    };
    let shZtMapping = {
      0: "待审核",
      1: "已审核",
    };
    total.value = res.data[0].total;
    tableData.value = K3FlXxList.map((material) => ({
      shZt: shZtMapping[material.shZt],
      zt: statusMapping[material.zt],
      id: material.id,
      gx: material.gx,
      sb: material.sb,
      banZu: material.banZu,
      bz: material.bz,
      documentNumber: material.documentNumber,
      djsj: material.djsj,
      sqrGh: material.sqrGh,
      sqrXm: material.sqrXm,
      sqrBm: material.sqrBm,
      sqSj: material.sqSj,
      shrGh: material.shrGh,
      shrXm: material.shrXm,
      shrBm: material.shrBm,
      shSj: material.shSj,
      shr: material.shr,
      xgrGh: material.xgrGh,
      xgrXm: material.xgrXm,
      xgrBm: material.xgrBm,
      xgSj: material.xgSj,
    }));
  });
};
selectpurposes();

const flushed = () => {
  showInsertButton.value = true;

  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  (checkList.value = ""), (checkList1.value = "");
  // 删除
  formDataList.value = [];
  // location.reload();
  page1.value = 1;
  limit1.value = 50;

  for (let a = 0; a < 20; a++) {
    addRow();
  }
};

// 修改业务员
const upButton = () => {
  dialogTableVisible3.value = true;
};

const handleBlur = (fieldName, rowIndex) => {
  const form = formDataList.value[rowIndex];
  const val = form[fieldName];
  validateAndFormat(form, fieldName, val);
};
const validateAndFormat = (form, prop, val) => {
  if (prop === "rs") {
    if (!Number.isInteger(Number(val))) {
      form[prop] = "";
    }
    return;
  }

  if (!isNaN(parseFloat(val)) && isFinite(val)) {
    form[prop] = parseFloat(val).toFixed(2);
  } else {
    form[prop] = "";
  }
};
// 修改
const updateMaterialsFixed = () => {
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  if (form.gx == "") {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "工序未填写",
      type: "error",
    });
    return;
  }
  if (form.sb == "") {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "设备未填写",
      type: "error",
    });
    return;
  }
  if (form.banZu == "") {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "班组未填写",
      type: "error",
    });
    return;
  }
  var openWindows = true;
  formDataList.value.forEach((formData, index) => {
    if (!formData.djBh == "") {
      console.log(1);
      if (
        formData.rs == "" ||
        formData.hcMc == "" ||
        formData.gg == "" ||
        formData.sl == "" ||
        formData.dw == ""
      ) {
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: "第" + (index + 1) + "行内容必填未填写",
          type: "error",
        });
        openWindows = false;
      }
    }
    return;
  });
  if (!openWindows) {
    return;
  }

  // 显示确认弹窗
  ElMessageBox.confirm("确认保存吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const filteredArray = formDataList.value.filter((item) => item.djBh.trim() !== "");
      axios({
        url: "/up/Date/Mc/Hc",
        method: "post",
        data: {
          id: idUpdate,
          gx: form.gx,
          sb: form.sb,
          banZu: form.banZu,
          bz: form.bz,
          documentNumber: form.documentNumber,
          zt: 7,
          userName: userName,
          formDataList: filteredArray,
          currentFormattedDateTime: currentFormattedDateTime,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.data,
            type: "success",
          });
          OFFdialogTableVisible();
          selectpurposes();
          return;
        }
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: res.data.msg,
          type: "error",
        });
      });
    })
    .catch(() => {});
};

// 新增
const insertMaterialsFixed = () => {
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  if (form.gx == "") {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "工序未填写",
      type: "error",
    });
    return;
  }
  if (form.sb == "") {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "设备未填写",
      type: "error",
    });
    return;
  }
  if (form.banZu == "") {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "班组未填写",
      type: "error",
    });
    return;
  }
  var openWindows = true;
  formDataList.value.forEach((formData, index) => {
    if (!formData.djBh == "") {
      console.log(1);
      if (
        formData.rs == "" ||
        formData.hcMc == "" ||
        formData.gg == "" ||
        formData.sl == "" ||
        formData.dw == ""
      ) {
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: "第" + (index + 1) + "行内容必填未填写",
          type: "error",
        });
        openWindows = false;
      }
    }
    return;
  });
  if (!openWindows) {
    return;
  }

  // 显示确认弹窗
  ElMessageBox.confirm("确认保存吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const filteredArray = formDataList.value.filter((item) => item.djBh.trim() !== "");
      axios({
        url: "/insert/McHy",
        method: "post",
        data: {
          gx: form.gx,
          sb: form.sb,
          banZu: form.banZu,
          bz: form.bz,
          zt: 7,
          userName: userName,
          formDataList: filteredArray,
          currentFormattedDateTime: currentFormattedDateTime,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.data,
            type: "success",
          });
          OFFdialogTableVisible();
          selectpurposes();
          return;
        }
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: res.data.msg,
          type: "error",
        });
      });
    })
    .catch(() => {});
};
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
interface Tree {
  label: string;
  children?: Tree[];
}

// 头部按钮
const selectedRows = ref([]);
const selectedRows2 = ref([]);

const table = ref();
const table2 = ref();

const rowTable = ref([]);
const handleSelectionChange2 = (val) => {
  selectedRows2.value = val;
};
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 审核
const handleWarning0 = () => {
  if (selectedRows.value.length != 0) {
    ElMessageBox.confirm("确认审核吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        const isAnyUnapproved = selectedRows.value.some((row) => row.shZt === "待审核");
        console.log(selectedRows.value);
        if (!isAnyUnapproved) {
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: "已审核的单据不能重复审核",
            type: "error",
          });
          return;
        }
        const userName = Cookies.get("userName");
        const currentFormattedDateTime = getCurrentFormattedDateTime();
        axios({
          url: "/up/Date/McHc/Sh",
          method: "post",
          data: {
            userName: userName,
            id: selectedRows.value.map((row) => row.id),
            zt: 2,
            currentFormattedDateTime: currentFormattedDateTime,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: res.data.data,
              type: "success",
            });
            selectpurposes();
            return;
          }
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.msg,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "请选择一行进行审核操作",
      type: "warning",
    });
    // ElMessage.warning("请选择一行进行审核操作");
  }
};
const handleWarning1 = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    ElMessageBox.confirm("确认弃审吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        const currentFormattedDateTime = getCurrentFormattedDateTime();
        const isAnyUnapproved = selectedRows.value.some((row) => row.shZt === "已审核");

        if (!isAnyUnapproved) {
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: "未审核的单据不能弃审",
            type: "error",
          });
          return;
        }
        axios({
          url: "/up/Date/McHc/Sh/QS",
          method: "post",
          data: {
            currentFormattedDateTime: currentFormattedDateTime,
            id: selectedRows.value.map((row) => row.id),
            userName: userName,
            menuId: menuId.value,
            zt: 7,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: res.data.data,
              type: "success",
            });
            selectpurposes();
            return;
          }
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.msg,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "请选择一行进行弃审操作",
      type: "warning",
    });
    // ElMessage.warning("请选择一行进行弃审操作");
  }
};
// 删除
const handleDelete = () => {
  if (selectedRows.value.length != 0) {
    ElMessageBox.confirm("确认退回吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        const userName = Cookies.get("userName");
        if (!userName) {
          router.push("/");
          return;
        }
        let shouldContinue = true; // 标志变量

        selectedRows.value.forEach((row, index) => {
          if (row.shZt === "待提交") {
            console.log(row);
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: `只能退回已提交的数据`,
              type: "error",
            });
            shouldContinue = false; // 设置标志变量为 false
          }
        });
        if (!shouldContinue) {
          return;
        }
        const currentFormattedDateTime = getCurrentFormattedDateTime();
        axios({
          url: "/MC/upDate/K3WlXx/ShZt10",
          method: "post",
          data: {
            currentFormattedDateTime: currentFormattedDateTime,
            userName: userName,
            djBh: selectedRows.value.map((row) => row.djBh),
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
              message: res.data.data,
              type: "success",
            });
            searchButton();
            return;
          }
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: res.data.msg,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "请选择一行进行删除操作",
      type: "warning",
    });
    // ElMessage.warning("请选择一行进行删除操作");
  }
};

// Main表格
const tableData = ref([]);
const tableData2 = ref([]);

// // 设置表头样式
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
const RowClick2 = (row, selection) => {
  table2.value.toggleRowSelection(row);
  // for (let i = 0; i < formDataList.value.length; i++) {
  //   if (formDataList.value[i].djBh === row.djBh) {
  //     const duplicateRowIndex = i + 1; // 行数从1开始
  //     ElMessage.error(`第 ${duplicateRowIndex} 行已经存在相同的单件编号:${row.djBh}`);
  //     return;
  //   }
  // }
  // formDataList.value[indexK3bm].djBh = row.djBh;
  // formDataList.value[indexK3bm].k3WlBm = row.k3WlBm;
  // formDataList.value[indexK3bm].k3Mc = row.k3Mc;
  // formDataList.value[indexK3bm].flMc = row.flMc;
  // formDataList.value[indexK3bm].lx = row.lx;
  // formDataList.value[indexK3bm].gzmDcMxcs = row.gzmDcMxcs;

  // dialogTableVisible2.value = false;
};
const cellStyle2 = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows2.value.find((selectedRow2) => selectedRow2.djBh === row.djBh)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
</script>
<style scoped>
/* 悬停 */
/* #f9f9fc, #fef5f0 */
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.custom-dialog {
  position: fixed;
  top: 12%;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 2px;
  left: 0;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 0; /* 设置横线的垂直位置，可以根据你的布局调整 */
}

.vertical-line3 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.5%; /* 设置横线的垂直位置，可以根据你的布局调整 */
  left: 0%;
}
.title {
  font-size: 18px;
}
.demo-pagination-block {
  float: right;
}
::v-deep .el-table .cell {
  padding: 0;
}
::v-deep .el-header {
  padding: 0;
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.buttonHeard {
  position: absolute;
  top: 0%;
  right: 1%;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}

.labs {
  margin-bottom: 0px;
}
/* 子表 */
.sticky-header {
  position: sticky;
  top: -1px;
  background-color: #ddd;
}

.table-header {
  border: 1px solid #ccc;
  background: rgb(225, 225, 230);
  z-index: 99;
  /* width: 50px; */
}

table tr td {
  /* width: 50px; */
  /* width: 10vh; */
  height: 30px;
}

table {
  border-collapse: collapse;
  /* border: 1px solid #ccc; */
  width: 100%;
}

input {
  border: 1px solid transparent;
}

td {
  border: 1px solid #ccc;
}

.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.4%; /* 设置横线的垂直位置，可以根据你的布局调整 */
}
.--el-dialog-padding-primary {
  padding: 0;
}
.table-value:hover {
  cursor: pointer;
  z-index: 11;
}
.red-asterisk {
  position: relative;
}
.red-asterisk::before {
  content: "*";
  color: red;
  /* position: absolute;
  left: px;
  top: 10px;
  margin-right: 4px; */
}
.dialogDiv {
  height: 600px;
  overflow: auto;
}
.flex-grow {
  flex-grow: 1;
}
.demo-basic .block:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
.demo-basic .block {
  flex: 1;
}
::-webkit-scrollbar {
  width: 5px;
}
.dialogDiv {
  position: relative;
  top: 10px;
}
</style>
